﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Web;
using HCDV;
using HCDV.HCSP;
using hrainwebbase.basecs;
//using System.Web.Script.Serialization;
//using System.Web.Security;

namespace hrainwebbase.ashx
{
    /// <summary>
    /// user_loginout 的摘要说明
    /// </summary>
    public class user_loginout : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {

        protected string callBackAction
        {
            get
            {
                if (GetParam("action") == null)
                    return string.Empty;
                else
                    return GetParam("action");
            }
        }
        public enum RequestType
        {
            Auto,
            Form,
            QueryString,
            Cookies
        }
        protected string GetParam(string name, RequestType requestType = RequestType.Auto)
        {
            if ((requestType == RequestType.Auto || requestType == RequestType.Form) && !string.IsNullOrEmpty(Mcontext.Request.Form[name]))
                return Mcontext.Request.Form[name];
            if ((requestType == RequestType.Auto || requestType == RequestType.QueryString) && !string.IsNullOrEmpty(Mcontext.Request.QueryString[name]))
                return Mcontext.Request.QueryString[name];
            if ((requestType == RequestType.Auto || requestType == RequestType.Cookies) && Mcontext.Request.Cookies[name] != null)
                return Mcontext.Request.Cookies[name].Value;
            return string.Empty;
        }

        protected HttpContext Mcontext;
        //C:\Program Files\MySQL\MySQL Server 5.5\bin
        // String appDirecroty = @"D:/Program Files/MySQL/MySQL Server 5.5/bin/";
        private static string mysqlwhere = "C:/Program Files/MySQL/MySQL Server 5.5/bin";
        public void ProcessRequest(HttpContext context)
        {
            //log = log4net.LogManager.GetLogger("user_loginout");
            Mcontext = context;
            Mcontext.Response.ContentType = "application/Json";
            try
            {

                switch (callBackAction)
                {
                    case "loginNew":
                    case "login":
                        if (callBackAction == "loginNew")
                        {
                            string cnum = context.Session["LoginCode"] == null ? "" : context.Session["LoginCode"].ToString();

                            if (GetParam("lcode").ToUpper() == cnum.ToUpper() && !string.IsNullOrEmpty(GetParam("lcode")))
                            {
                                //return true;
                            }
                            else
                            {
                                Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Fail, JsonControl.GetJsonStr("验证码不正确")));
                                return;
                            }
                        }
                        userloginout ul = new userloginout();
                        string lusername = GetParam("lusername");
                        string luserpass = GetParam("luserpass");
                        DataTable user;
                        Hashtable allinfo = new Hashtable();
                        allinfo.Add("userid", lusername);
                        using (dbsimple db = new dbsimple())
                        {
                            string ipwhere = "";
                            DataTable dt = db.Query("select id,fv3 from  table_sp where type=20151030 and fv1='" + IPAddress + "' and fv2='" + lusername + "'");
                            if (dt == null || dt.Rows.Count == 0)
                            {

                                try
                                {
                                    ipwhere = new webInfo().GetIPAdress(IPAddress);
                                }
                                catch (Exception ee)
                                { }
                                //delete from table_sp where typename like '%来访%'
                                db.SpExe("insert into table_sp (type,typename,fv1,addtime,fv2,nv1,fv3)values(20151030,'来访登记','" + IPAddress + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + lusername + "',1,'" + ipwhere + "')");
                            }
                            else
                            {
                                ipwhere = dt.Rows[0][1].ToString();
                                if (string.IsNullOrEmpty(ipwhere))
                                    ipwhere = new webInfo().GetIPAdress(IPAddress);
                                db.SpExe("update table_sp  set nv1=nv1+1,dt1='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',fv3='" + ipwhere + "'   where id=" + dt.Rows[0][0].ToString());
                            }
                            user = db.getProc("getuserbylid", allinfo).Tables[0];
                        }
                        string erinfo = "";
                        if (user == null || user.Rows.Count == 0)
                        {
                            erinfo = "账号不存在";
                        }
                        else
                        {
                            DataRow row = user.Rows[0];
                            if (row["password"].ToString().Equals(luserpass))
                            {
                                LoginUser lu = new LoginUser();
                                lu.UserId = row["empid"].ToString();
                                lu.OrgCode = row["SimpleCode"].ToString();
                                lu.UserName = lusername;
                                lu.UserDep = row["DepId"].ToString();
                                lu.UserOrg = row["branchId"].ToString();
                                lu.BranchType = row["branchType"].ToString();
                                lu.UserTitle = row["roles"].ToString();
                                lu.UserDepName = row["depname"].ToString();
                                lu.UserOrgName = row["branchname"].ToString();
                                Mcontext.Session["LoginUser"] = lu;
                                Mcontext.Session["EmpID"] = row["empid"].ToString();
                                if (Mcontext.Request.Browser.Browser.ToUpper().Contains("IE"))
                                    Mcontext.Response.Headers.Add("P3P", "CP=CAO PSA OUR");
                                Mcontext.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", Mcontext.Session.SessionID));
                                Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr("登录成功")));
                            }
                            else
                            { erinfo = "密码不正确"; }

                        }
                        if (!String.IsNullOrEmpty(erinfo))
                        { Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Fail, JsonControl.GetJsonStr(erinfo))); }


                        break;
                    case "loginout":
                        Mcontext.Session.Remove("LoginUser");
                        Mcontext.Session.Remove("EmpID");
                        Mcontext.Response.Cookies.Clear();
                        Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr("登出成功")));
                        break;
                    case "savedb":
                        if (GetParam("user") == null || GetParam("user") != "hechaohechao")
                        {
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr("哈,你不是管理人员，不能备份噢")));
                        }
                        else
                        {
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr(Backup())));
                        }
                        break;
                    case "backdb":
                        if (GetParam("user") == null || GetParam("user") != "hechaohechao")
                        {
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr("哈,你不是管理人员，不能还原噢")));
                        }
                        else
                        {
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr(Restore())));
                        }
                        break;
                    case "indexin":
                        using (dbsimple db = new dbsimple())
                        {
                            string ipwhere = "";
                            DataTable dt = db.Query("select id,fv3 from  table_sp where type=2015103001 and fv1='" + IPAddress + "'");
                            if (dt == null || dt.Rows.Count == 0)
                            {

                                try
                                {
                                    ipwhere = new webInfo().GetIPAdress(IPAddress);
                                    // ipwhere = new webInfo().GetIPAdress("183.13.102.8");
                                }
                                catch (Exception ee)
                                { }
                                db.SpExe("insert into table_sp (type,typename,fv1,addtime,nv1,fv3)values(2015103001,'来访','" + IPAddress + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',1,'" + ipwhere + "')");
                            }
                            else
                            {
                                ipwhere = dt.Rows[0][1].ToString();
                                if (string.IsNullOrEmpty(ipwhere) || ipwhere.Length < 5)
                                    ipwhere = new webInfo().GetIPAdress("183.13.102.87");
                                db.SpExe("update table_sp  set nv1=nv1+1,dt1='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',fv3='" + ipwhere + "'   where id=" + dt.Rows[0][0].ToString());
                            }




                        }
                        Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr("成功")));
                        break;
                    default:
                        context.Response.Write("{\"msg\":\"参数错误！\",\"success\":false}");
                        break;
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError("user_loginout", ex);
                context.Response.Write("{\"msg\":\"" + ex.Message + "\",\"success\":false}");
            }
        }


        protected string Backup()
        {
            try
            {
                //string filename = DateTime.Now.ToString().Replace("-", "").Replace(":", "").Replace(" ", "");

                string filePath = "C://hcdb";
                string fileName = filePath + "//newbaseaccess.sql";//备份的文件名称和路径
                //判断目录是否存在
                if (!System.IO.File.Exists(fileName))
                {
                    System.IO.Directory.CreateDirectory(filePath);
                }

                //构建执行的命令
                String command = string.Format("mysqldump --quick --host=localhost --default-character-set=utf8  --lock-all-tables --port=3306 --user=root --password=root --databases newbaseaccess -R >C://hcdb//{0}.sql", "newbaseaccess");

                //获取mysqldump.exe所在路径
                //C:\Program Files\MySQL\MySQL Server 5.5\bin
                String appDirecroty = mysqlwhere;

                StartCmd(appDirecroty, command);
                return "数据库已成功备份";
            }
            catch (Exception ex)
            {
                return "数据库备份失败" + ex.Message;
            }
        }
        protected string Restore()
        {
            try
            {


                //构建执行的命令
                String command = string.Format("mysql --host=localhost --default-character-set=utf8 --port=3306 --user=root --password=root newbaseaccess <C://hcdb//{0}.sql", "newbaseaccess");

                //获取mysql.exe所在路径
                String appDirecroty = mysqlwhere;

                StartCmd(appDirecroty, command);
                return "服务器数据库还原成功！";
            }
            catch (Exception ex)
            {
                return "数据库还原失败" + ex.Message;
            }
        }

        /// <summary>
        /// 执行Cmd命令
        /// </summary>
        /// <param name="workingDirectory">要启动的进程的目录</param>
        /// <param name="command">要执行的命令</param>
        public static void StartCmd(String workingDirectory, String command)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.WorkingDirectory = workingDirectory;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.WriteLine(command);
            p.StandardInput.WriteLine("exit");
        }
        public static string IPAddress
        {
            get
            {
                string userIP;
                // HttpRequest Request = HttpContext.Current.Request;  
                HttpRequest Request = HttpContext.Current.Request; // ForumContext.Current.Context.Request;  
                // 如果使用代理，获取真实IP  
                if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
                    userIP = Request.ServerVariables["REMOTE_ADDR"];
                else
                    userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (userIP == null || userIP == "")
                    userIP = Request.UserHostAddress;
                return userIP;
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}